# -*- coding: utf-8  -*-
# Final Statistics Bot - A Free bot working on MediaWiki. In Arabic
# Wikipedia, it works at 00:00 first day of every month using cron.
# 00 00 1 * * cd pywikipedia && python finalstat.py
#
# Copyright (C) 2009 Osama Khalid (osamak.wfm@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Please report bugs and help improving this program by connecting
# <OsamaK.WFM@gmail.com>.
import re, datetime, wikipedia, okbot

class finalStat:
  def __init__(self):
    self.site = wikipedia.getSite()
    ArabicMonths = [u"يناير", u"فبراير", u"مارس", u"أبريل", u"مايو", u"يونيو", u"يوليو", u"أغسطس", u"سبتمبر", u"أكتوبر", u"نوفمبر", u"ديسمبر"]
    self.ArabicMonth = ArabicMonths[(datetime.datetime.today() - datetime.timedelta(days = 1)).month - 1] #Last day's month (Last month).
    self.statTitle = u"مستخدم:OsamaK/إحصاءات/" + self.ArabicMonth + " " + str((datetime.datetime.today() - datetime.timedelta(days = 1)).year)
    print self.statTitle

  def run(self):
    statPageText = wikipedia.Page(self.site, self.statTitle).get()
    recordsNumber = statPageText.count(self.ArabicMonth) # How many records are there? (supposedly == the number of days in the month)
    print recordsNumber
    diffs = self.findDiff(statPageText)
    sums = self.findSums(statPageText)
    finalStatInfo = self.formatFinalStat(diffs, sums, recordsNumber)
    self.addFinalStat(statPageText, finalStatInfo)

  def findDiff(self, statPageText):
    pages_diff = sum([int(i[0]) for i in re.findall(re.compile(ur'\|فرق الصفحات = (?P<pages_diff>(-)?\d+)'), statPageText)][1:])
    articles_diff = sum([int(i[0]) for i in re.findall(re.compile(ur'\|فرق المقالات = (?P<articles_diff>(-)?\d+)'),statPageText)][1:])
    edits_diff = sum([int(i[0]) for i in re.findall(re.compile(ur'\|فرق التعديلات = (?P<edits_diff>(-)?\d+)'), statPageText)][1:])
    users_diff = sum([int(i[0]) for i in re.findall(re.compile(ur'\|فرق المستخدمين = (?P<users_diff>(-)?\d+)'), statPageText)][1:])
    files_diff = sum([int(i[0]) for i in re.findall(re.compile(ur'\|فرق الصور = (?P<files_diff>(-)?\d+)'), statPageText)][1:])    
    return {'pages_diff':pages_diff, 'articles_diff':articles_diff, 'edits_diff':edits_diff, 'users_diff':users_diff, 'files_diff':files_diff}

  def findSums(self, statPageText):
    protections_sum = sum([int(i[0]) for i in re.findall(re.compile(ur'\|الحماية = (?P<protections_sums>(-)?\d+)'), statPageText)][1:])
    deletions_sum = sum([int(i[0]) for i in re.findall(re.compile(ur'\|الحذف = (?P<deletions_sums>(-)?\d+)'), statPageText)][1:])
    return {'protections_sum':protections_sum, 'deletions_sum':deletions_sum}

  def formatFinalStat(self, diffs, sums, recordsNumber):
    finalStatInfo = {}
    finalStatInfo.update(diffs)
    finalStatInfo.update(sums)
    for key in diffs.keys():# Adding the average which is the rounding of the result of dividing the sum by the number of records.
      finalStatInfo.update({key+'_avrg': round(diffs[key] / (recordsNumber - 1.0), 1)})
    for key in sums.keys():
      finalStatInfo.update({key+'_avrg': round(sums[key] / (recordsNumber - 1.0), 1)})
      
    return finalStatInfo

  def addFinalStat(self, statPageText, finalStatInfo):
    finalStatTemplate = u"""\n\n
{{مستخدم:OsamaK/إحصاءات/محصلة
|زيادة الصفحات = %(pages_diff)s
|معدل زيادة الصفحات = %(pages_diff_avrg)s
|زيادة المقالات = %(articles_diff)s
|معدل زيادة المقالات = %(articles_diff_avrg)s
|زيادة التعديلات = %(edits_diff)s
|معدل زيادة التعديلات = %(edits_diff_avrg)s
|زيادة المستخدمين = %(users_diff)s
|معدل زيادة المستخدمين = %(users_diff_avrg)s
|زيادة الملفات = %(files_diff)s
|معدل زيادة الملفات = %(files_diff_avrg)s
|مجموع الحذف = %(deletions_sum)s
|معدل الحذف = %(deletions_sum_avrg)s
|مجموع الحماية = %(protections_sum)s
|معدل الحماية = %(protections_sum_avrg)s
}}"""
    finalStatTemplate = finalStatTemplate % finalStatInfo
    statPageText = statPageText + finalStatTemplate
    okbot.put_page(self.site, wikipedia.Page(self.site, self.statTitle), statPageText, u'روبوت: إضافة محصلة الإحصاءات')

if __name__ == '__main__':
  try:
    bot = finalStat()
    bot.run()
  finally:
    wikipedia.stopme()
